import { defineStore } from 'pinia'
import { Toast, Dialog } from "vant";

export const useBookread = defineStore('bookread', {
    state: () => ({
        book: { list: [], reverseList: [], },//书

        keyword: "",//关键字
        isReverse: false,//是否反转目录
        main: false, //主控制弹窗
        directoryMark: false, //目录和标签弹窗
        directoryMarkType: 'directory',//默认显示是目录
        adjust: false, // 调整弹窗
        infoFuns: false, // 更多弹窗
        fontPop: false, // 选择字体的弹窗
        downloadDialogFlag: false,//下载清单的弹窗
        CommentPopFlag: false,//评论的弹窗

        autoSubscribeChecked: false, //自动订阅开关
        brightValue: 94, //亮度
        scrollRatio: 0,// 滚动条比值
        lineHeight: 1.8,//行高
        lettterSpacing: 0,//间距
        size: 16,//字体大小
        family: "'微软雅黑'",// 字体样式
        theme: "green",// 主题
        hsObj: { bgColor: { h: 228, s: 16 }, color: { h: 0, s: 0 } }, // 主题调节

        current: 0,//看到的章节
        markList: [], //书签列表
        rateFreeValue: 0,// 免费投票
        rateFreeFlag: false,// 投票标识
        rateMoneyValue: 0,// 付费投票
        historyList: [], // 浏览章节历史
        downloadList: [],// 已下载列表
        tobeDownloadList: [], //将要下载的列表
        payList: [],// 已支付的章节数据
        ModifyList: [],// 已修改过的数据 评论功能受益

    }),
    actions: {

        // 更新修改数组
        updateModifyList() {
            // 请代理 减少修改次数
            let proxyList = JSON.parse(JSON.stringify(this.ModifyList))

            // 先过滤出来 防止重复
            proxyList = proxyList.filter(item => item.title != this.book.list[this.current].title);

            // 将已经修改过的数据存进该数组
            proxyList.push(JSON.parse(JSON.stringify(this.book.list[this.current])))

            // 最后重新赋值更新界面
            this.ModifyList = proxyList;
        },

        // 添加评论
        addComment(text) {
            let obj = {
                "id": new Date().getTime(),
                "content": text,
                "user": {
                    "id": "billkes",
                    "nickname": "billkes",
                    "avatar": "http://billkes.eombrx.top/img/five.jpg"
                },
                "status": 1,
                "like_count": 0,
                "sub_comment_count": 0,
                "reply_to": {
                    "id": "",
                    "user_id": "",
                    "user_nickname": "",
                    "user_avatar": ""
                },
                "lesson_id": "6335baac8d555800061883d8",
                "my_like": false,
                "updated_at": 1665336384,
                "created_at": 1665330351
            }

            // 更修数据 页面更新 后续不再需要 
            this.book.list[this.current].commentList.push(obj);

            this.updateModifyList();
        },

        // 切换喜欢方法
        toggleLikeFun(id) {

            // 防止没有数据  数据同步
            let obj = this.ModifyList.find(item => item.title == this.book.list[this.current].title);
            if (obj) {
                this.book.list[this.current] = obj;
            }


            let index = this.book.list[this.current].commentList.findIndex(item => item.id == id);
            // console.log(index);
            this.book.list[this.current].commentList[index].my_like = !this.book.list[this.current].commentList[index].my_like;
            this.book.list[this.current].commentList[index].like_count = this.book.list[this.current].commentList[index].my_like ? this.book.list[this.current].commentList[index].like_count + 1 : this.book.list[this.current].commentList[index].like_count - 1;

            this.updateModifyList();
        },

        // 删除指定标签
        delMarkFun(current) {
            // 直接过滤掉
            this.markList = this.markList.filter(item => item.current != current);
        },

        // 下载后续已购章节
        downloadFun1() {
            Toast.loading({
                duration: 0,
                forbidClick: true,
                message: '请稍等',
                onOpened: () => {
                    this.tobeDownloadList = [];
                    const timer = setInterval(() => {
                        if (this.tobeDownloadList) {
                            clearInterval(timer);
                            Toast.clear();
                        }
                    }, 100);
                    this.tobeDownloadList = this.book.list.filter((item, index) =>
                        index > this.current &&
                        !item.isLock &&
                        !this.downloadList.some(t => t == item.title)
                    ).map(item => item.title);

                    // console.log(this.tobeDownloadList);
                    this.downloadDialogFlag = true;
                }
            });
        },
        downloadFun2(list) {
            this.downloadList = list.concat(this.downloadList);
            Toast.success('下载成功');
            this.closeAll();
            // console.log(this.downloadList);
        },

        // 记录浏览历史
        recordHistorical() {
            let arr = this.historyList.filter(o => o.current != this.current)

            let contentList = this.book.list[this.current].contentList;

            arr.unshift({ current: this.current, time: new Date().getTime(), contentList })
            // console.log(arr);
            this.historyList = arr;
        },

        // 添加标签方法
        addMark() {
            if (!this.keyword || !this.scrollRatio)
                return Toast("您的标签没有重点\n关键字:空空如也...")

            this.markList.unshift({
                current: this.current,
                scrollRatio: this.scrollRatio,
                keyword: this.keyword,
            });
            Toast("添加成功");
        },

        // 转到标签
        goMark(index, e) {
            let { current, scrollRatio, } = this.markList[index]
            this.$patch({ current, scrollRatio })
            this.closeAll();

            // console.log(e);
            let pathIndex = 0;
            for (let i = 0; i < e.path.length; i++) {
                if (e.path[i].className == "BookRead") {
                    pathIndex = i
                    break
                }
            }
            let view = e.path[pathIndex].querySelector(".content");

            // 获取内容视口的高度
            let viewHeight = view.offsetHeight;
            // 获取内容实际的高度
            let contentHeight = view.firstElementChild.offsetHeight;
            // 计算出高度差
            let dHeight = contentHeight - viewHeight;
            // 计算出滚动的top值比值
            let scrollTop = scrollRatio * dHeight;
            // 重新赋值
            view.scrollTop = scrollTop;

            // 记录浏览历史
            this.recordHistorical()

        },

        // 支付方法
        pay(current, e) {
            const beforeClose = (action) =>
                new Promise((resolve) => {

                    setTimeout(() => {

                        if (action === 'confirm') {
                            let userinfo = JSON.parse(window.localStorage.getItem("userinfo"))
                            if (userinfo) {
                                if (userinfo.foxBean >= 50) {
                                    Toast({
                                        message: '支付成功',
                                        icon: 'certificate',
                                    });
                                    this.book.list[current].isLock = false;
                                    let title = this.book.list[current].title;
                                    this.payList.filter(title => title != this.book.list[current].title);
                                    this.payList.push(title);

                                    // console.log(current, e, true);
                                    this.goPage(current, e, true);
                                    userinfo.foxBean -= 50
                                    window.localStorage.setItem("userinfo", JSON.stringify(userinfo))
                                    resolve(true);

                                } else {
                                    Toast("狐豆不足，请及时充值")
                                    Dialog.close();
                                    resolve(false);
                                }
                            }

                        } else {
                            // 拦截取消操作 
                            Toast({
                                message: '取消支付',
                                icon: 'warn-o',
                            });
                            Dialog.close();
                            resolve(false);
                        }
                    }, 300);
                });

            Dialog.confirm({
                title: '下一章为付费内容',
                message:
                    `是否花费50豆购买\n${this.book.list[current].title}`,
                beforeClose,
            });
        },

        // 取到指定章节页
        goPage(val, e, flag) {
            // flag为 true 直接跳到指定章节 为false 递增递减跳

            // console.log(val, flag);

            let proxy = 0;
            if (flag) {
                // 请代理 
                proxy = val;
                // 判断是否反转了
                // if (this.isReverse) proxy = this.book.list.length - 1 - val;
            } else {
                proxy = this.current;
                proxy += val;
                if (proxy <= -1) { proxy = 0; Toast("已经是第一章") }
                else if (proxy >= this.book.list.length) { proxy = this.book.list.length - 1; Toast("已经是最后一章") }
            }

            // console.log(this.book.list[proxy]);
            if (this.book.list[proxy].isLock && !this.payList.some(v => v == this.book.list[proxy].title)) {
                this.closeAll();
                return this.pay(proxy, e);
            } else {
                // console.log(this.current, proxy);
                // 加入加载中动画 模拟请求数据

                // 如果开启了自动订阅
                if (this.autoSubscribeChecked) {
                    if (proxy != this.current + 1 && proxy != this.current - 1 && proxy != 0 && proxy != this.book.list.length - 1) {
                        Toast.loading({
                            duration: 500,
                            forbidClick: true,
                            message: '请稍等',
                            onOpened: () => {
                                this.current = proxy;
                            }
                        });
                    } else this.current = proxy;
                } else {
                    Toast.loading({
                        duration: 500,
                        forbidClick: true,
                        message: '请稍等',
                        onOpened: () => {
                            this.current = proxy;
                        }
                    });
                }

                // console.log(this.current);
            }

            this.recordHistorical();

            this.closeAll();

            // 回到顶部
            let pathIndex = 0;
            // console.log(typeof e);
            if (typeof e == 'boolean') return;
            for (let i = 0; i < e.path.length; i++) {
                if (e.path[i].className == "BookRead") {
                    pathIndex = i
                    break
                }
            }
            let view = e.path[pathIndex].querySelector(".content");

            // 重新赋值top
            view.scrollTop = 0;

        },

        // 设置字体大小
        setSize(val) {
            let size = this.size;

            if (val > 0) size += 2;
            else size -= 2;

            if (size <= 12) size = 14
            else if (size >= 24) size = 22

            this.size = size;
        },

        // 设置字体行高和间距
        setSpace(val) {
            let lineHeight = this.lineHeight;
            let lettterSpacing = this.lettterSpacing;

            if (val > 0) {
                lineHeight += 0.2;
                lettterSpacing += 2;
            } else {
                lineHeight -= 0.2;
                lettterSpacing -= 2;
            }

            if (lineHeight >= 2.4) lineHeight = 2.2
            else if (lineHeight <= 1.2) lineHeight = 1.4

            if (lettterSpacing <= -2) lettterSpacing = 0
            else if (lettterSpacing >= 8) lettterSpacing = 6



            this.lineHeight = lineHeight;
            this.lettterSpacing = lettterSpacing;
        },

        // 关闭所有弹窗
        closeAll() {
            this.main = false;
            this.directoryMark = false;
            this.adjust = false;
            this.infoFuns = false;
            this.fontPop = false;
        },

        // 显示主空状态
        showControlMain() {
            if (this.main || this.directoryMark || this.adjust || this.infoFuns || this.fontPop) return;
            // console.log(this.main, this.directoryMark, this.adjust, this.infoFuns, this.fontPop);
            if (!this.main) this.main = true;//主控制弹窗
        }
    },
    getters: {

    },
})